package com.hns.can.upgrade.service;

import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hns.can.base.entity.SysCorpInfoEntity;
import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.aop.orgTree.LeftOrgAnnotation;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.common.formula.FillParamsVo;
import com.hns.can.master.entity.BaseCarInfoEntity;
import com.hns.can.master.entity.BaseEqmtInfoEntity;
import com.hns.can.master.entity.BaseLineInfoEntity;
import com.hns.can.master.service.WebServiceBSService;
import com.hns.can.master.upgrade.UpgradeProcessor;
import com.hns.can.upgrade.entity.UpgEqmtIssuedParamTemp;
import com.hns.can.upgrade.entity.UpgEqmtVrsnManageInfo;
import com.hns.can.upgrade.entity.UpgEqmtVrsnManageLog;
import com.hns.can.upgrade.entity.UpgEqmtVrsnParamDetail;
import com.hns.can.upgrade.enumrate.UpgradeVersionTypeEnum;
import com.hns.can.upgrade.upgrade.DevLogUploadProcessor;
import com.hns.can.upgrade.vo.UpgEqmtIssuedParamVo;
import com.hns.can.upgrade.vo.UpgradeVo;
import com.hns.can.upgrade.vo.WebServiceVo;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.DateTool;
import com.hns.tool.pub.FTPUtils;
import com.hns.tool.pub.JsonUtil;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.TxtUtil;
import com.hns.tool.pub.UtilConfig;
import com.hns.tool.pub.UtilString;
/**
 * 升级文件设置
 * @author:lan
 * @email:763836737@qq.com
 * @version Revision 2.0.0
 */
@Service
public class UpgradeFileSetService extends CommonService {
    
	/**
	 * 填充代码描述
	 */
    @Autowired
    private FillCodeDscValue codeDscValue;
    @Autowired
    private WebServiceBSService webServiceBSService; // 注入WebServiceBSService
    @Autowired
    private TaskExecutor taskExecutor;

    /**
     * 查询升级文件设置
     * @param vo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public Pagination getFileSetPage(UpgradeVo vo) throws Exception{
        SysUserEntity user = this.getCurrentUser().getUser();
        String corpId = user.getCorpId();
        vo.setCorpId(corpId);
        Pagination page = this.myBatisPage("upgrade.getFileSetCnt","upgrade.getFileSetList", vo,UpgEqmtVrsnManageInfo.class);
        // 数据处理
        Map<String, Object> rstMap = null;
        String ftpUpgradeAdr = "";
        List<Object> list = page.getData();
        if(PubUtil.isNotEmpty(list)){
            for(int i = 0; i < list.size(); i++){
                UpgEqmtVrsnManageInfo entity = (UpgEqmtVrsnManageInfo)list.get(i);
                rstMap = this.getFtpUpgradeAddrInfo(entity);
                ftpUpgradeAdr = "" + rstMap.get("ftpUpgradeDire") + rstMap.get("ftpUpgradeFile");
                entity.setFtpUpgradeAdr(ftpUpgradeAdr);
            }
        }
        Map<String,String> map = new HashMap<String,String>();
        map.put("licPltNo", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo1 = new FillParamsVo("carId", map);
        map = new HashMap<String,String>();
        map.put("lineName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("lineId", map);
        codeDscValue.fillInfoValue(page.getData(), new String[]{GlobalConst.CACHE_KEY_BASE_CAR_INFO, GlobalConst.CACHE_KEY_BASE_LINE_INFO}, vo1, vo2);
        return page;
    }

    /**
     * 查询升级命令设置
     * @param vo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public Pagination getByFilePage(UpgradeVo vo) throws Exception{
        SysUserEntity user = this.getCurrentUser().getUser();
        String corpId = user.getCorpId();
        vo.setCorpId(corpId);
        Pagination page = this.myBatisPage("upgrade.getAppMgrCnt","upgrade.getAppMgrList", vo,UpgEqmtVrsnManageInfo.class);
        return page;
    }

    /**
     * @param entity
     * @return
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-10-17
     * @功能说明：获取ftp地址
     */
    public Map<String, Object> getFtpUpgradeAddrInfo(UpgEqmtVrsnManageInfo entity){
        String addr = "";
        if(UpgradeVersionTypeEnum.APP_UPGVS.getFlag().equals(entity.getVrsnType())) {
            if(UpgradeVersionTypeEnum.CORE_BOARD.getFlag().equals(entity.getAppUpgrade())){ // 核心板应用
                addr =  UtilConfig.getString("ftp_update_center_coreboard");
            }else if(UpgradeVersionTypeEnum.MAIN_BOARD.getFlag().equals(entity.getAppUpgrade())) {
                addr = UtilConfig.getString("ftp_update_center_mainboard");
            }
        }else if(UpgradeVersionTypeEnum.LINE_UPGVS.getFlag().equals(entity.getVrsnType())){
            SysCorpInfoEntity corp = getSysCorpInfoByCorpId(entity.getCorpId());
            BaseLineInfoEntity line = getBaseLineInfoByLineId(entity.getLineId());
            if(line!=null){
                addr = UtilConfig.getString("ftp_update_center_lineconfig")+corp.getCorpEngAb()+"/"+line.getLineCode()+"/";
            }
        }else if(UpgradeVersionTypeEnum.CAN_UPGVS.getFlag().equals(entity.getVrsnType())){
            addr = UtilConfig.getString("ftp_update_center_parmconfig") + entity.getLineId()+ "/";
        }else if(UpgradeVersionTypeEnum.COMM_UPGVS.getFlag().equals(entity.getVrsnType())){
            addr = UtilConfig.getString("ftp_update_center_parmconfig") + entity.getCarId()+ "/";
        }else if(UpgradeVersionTypeEnum.PERI_UPGVS.getFlag().equals(entity.getVrsnType())){
            addr = UtilConfig.getString("ftp_update_center_parmconfig") + entity.getCarId()+ "/";
        }else if(UpgradeVersionTypeEnum.STATE_UPGVS.getFlag().equals(entity.getVrsnType())){
            addr = UtilConfig.getString("ftp_update_center_parmconfig") + entity.getCarId()+ "/";
        }else if(UpgradeVersionTypeEnum.CAR_CANUPGVS.getFlag().equals(entity.getVrsnType())){
            addr = UtilConfig.getString("ftp_update_center_canconfig");
        }
        String ftpUpgradeDire = addr + entity.getVrsnName()+"/";
        String ftpUpgradeFile = entity.getFtpUpgradeAdr();
        Map<String, Object> rstMap = new HashMap<String, Object>();
        rstMap.put("ftpUpgradeDire", ftpUpgradeDire);
        rstMap.put("ftpUpgradeFile", ftpUpgradeFile);
        return rstMap;
    }

    /**
     * @param corpId
     * @return
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-9-29
     * @功能说明：获得企业的信息
     */
    @Transactional
    public SysCorpInfoEntity getSysCorpInfoByCorpId(String corpId){
        SysCorpInfoEntity entity = commonEntityDao.find(corpId, SysCorpInfoEntity.class);
        return entity;
    }

    /**
     * @return
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-9-29
     * @功能说明：获得线路的信息
     */
    @Transactional
    public BaseLineInfoEntity getBaseLineInfoByLineId(String lineId){
        BaseLineInfoEntity entity = commonEntityDao.find(lineId, BaseLineInfoEntity.class);
        return entity;
    }

    /**
     * 添加应用程序
     * @param entity
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public void addAppMgr(UpgEqmtVrsnManageInfo entity) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        String corpId = user.getCorpId();
        entity.setCorpId(corpId);
        entity.setVrsnId(UtilString.getUUID());
        //上传日期
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        entity.setUploadDate(df.format(new Date()));
        entity.setCrtTime(new Date());
        entity.setCrtUser(user.getAcctName());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        entity.setCarModel(entity.getCarModel());
        // -- 版本名称唯一性
        Integer count = (Integer) sqlMapDao.selectOne("upgrade.checkVrsnName", entity);
        if(count > 0){
            throw new BusinessException(MsgType.WARN.getFlag(),"您输入的版本名称已经存在！");
        }
        commonEntityDao.save(entity);
    }

    /**
     * 获取车辆型号
     * @param entity
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("unchecked")
    public List<BaseCarInfoEntity> getCarModel(BaseCarInfoEntity entity) {
        List<BaseCarInfoEntity> list = PubUtil.convertListMapToObject(
            this.sqlMapDao.selectList("upgrade.getCarModel", entity), BaseCarInfoEntity.class);
        return list;
    }


    /**
     * @param entity
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-9-19
     * @功能说明：新增线路
     */
    @Transactional
    public void addLineMgr(UpgEqmtVrsnManageInfo entity) throws Exception{
        SysUserEntity user = this.getCurrentUser().getUser();
        String corpId = user.getCorpId();
        entity.setCorpId(corpId);
        entity.setVrsnId(UtilString.getUUID());
        //版本类型
        entity.setVrsnType(UpgradeVersionTypeEnum.LINE_UPGVS.getFlag());
        //上传日期
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        entity.setUploadDate(df.format(new Date()));
        entity.setCrtTime(new Date());
        entity.setCrtUser(user.getAcctName());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        // -- 版本名称唯一性
        Integer count1 = (Integer) sqlMapDao.selectOne("upgrade.checkVrsnName", entity);
        if(count1 > 0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的版本名称已经存在！");
        }
        commonEntityDao.save(entity);
    }

    /**
     *
     * @param vo
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-10-23
     * @功能说明：命令升级
     */

    public void addCanMgr(UpgradeVo vo,List<BaseEqmtInfoEntity> list) throws Exception {
        //循环下发每辆车
        for (int i = 0; i < list.size() ; i++) {
            WebServiceVo vo2 = new WebServiceVo();
            vo2.setParamList(vo.getList());
            vo2.setDevId(list.get(i).getEqmtCd());
            vo2.setType("1");
            vo2.setParamId(vo.getAppUpgrade());
            String lockCarJson=JsonUtil.getJsonStringFromObject(vo2);
            //String upgradeCommandStr = "{'devId': '"+ vo.getEqmtCdArr()[i] +"','canId': '05', 'type':'0','folder':'"+ ftpUpgradeDirePath +"','file': '"+ ftpUpgradeFileName +"','module': '"+ vo.getModule() +"'}";
            UpgradeProcessor processor = new UpgradeProcessor("1E", lockCarJson, taskExecutor);
            processor.process();
           // webServiceBSService.sendToCommModel(lockCarJson, "1E");
        }
    }
    /**
     *
     * @param vo
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-10-23
     * @功能说明：循环下发
     */
    @Transactional
    public List<BaseEqmtInfoEntity> saveLog(UpgradeVo vo) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        vo.setCorpId(user.getCorpId());
        Integer count1 = (Integer) sqlMapDao.selectOne("upgrade.checkVrsnName", vo);
        if(count1 > 0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的版本名称已经存在！");
        }
        //获取线路下所有车的设备编码
        List<BaseEqmtInfoEntity> list = PubUtil.convertListMapToObject(
                this.sqlMapDao.selectList("upgrade.getEqmtCdByCarID", vo), BaseEqmtInfoEntity.class);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat dfhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        vo.setUploadDate(df.format(new Date()));
        UpgEqmtVrsnManageInfo infoEntity = new UpgEqmtVrsnManageInfo();
        infoEntity.setVrsnId(UtilString.getUUID());
        infoEntity.setCorpId(user.getCorpId());
        infoEntity.setVrsnName(vo.getVrsnName());
        infoEntity.setVrsnType(vo.getAppUpgrade());
        infoEntity.setUploadDate(df.format(new Date()));
        infoEntity.setAppUpgrade(vo.getAppUpgrade());
        //infoEntity.setFtpUpgradeAdr("state.conf");
        infoEntity.setLineId(vo.getLineId());
        infoEntity.setCarId(vo.getCarId());
        infoEntity.setCrtTime(new Date());
        infoEntity.setCrtUser(user.getAcctName());
        infoEntity.setUpdateTime(new Date());
        infoEntity.setUpdateUser(user.getAcctName());
        commonEntityDao.save(infoEntity);//保存设备版本管理信息实体类
        vo.setVrsnId(infoEntity.getVrsnId());
        for (int i = 0; i <vo.getList().size(); i++) {
            UpgEqmtVrsnParamDetail detailEntity = new UpgEqmtVrsnParamDetail();
            detailEntity.setDetailId(UtilString.getUUID());
            detailEntity.setVrsnId(vo.getVrsnId());
            detailEntity.setParamName(vo.getList().get(i).getParamName());
            detailEntity.setParamValue(vo.getList().get(i).getParamValue());
            detailEntity.setSn(vo.getList().get(i).getSn().add(new BigDecimal(1)));
            commonEntityDao.save(detailEntity);//保存设备参数版本明细实体
        }
        switch (vo.getAppUpgrade()) {
            case "5": vo.setType("ULOG0011");
                break;
            case "6": vo.setType("ULOG0012");
                break;
            case "7": vo.setType("ULOG0013");
                break;
            case "8": vo.setType("ULOG0014");
                break;
            case "9": vo.setType("ULOG0015");
                break;
            case "10": vo.setType("ULOG0016");
                break;
            case "11": vo.setType("ULOG0017");
                break;
        }
        for (int i = 0; i < list.size() ; i++) {
            UpgEqmtVrsnManageLog logEntity = new UpgEqmtVrsnManageLog();
            logEntity.setLogId(UtilString.getUUID());
            logEntity.setLogType(vo.getType());
            logEntity.setCorpId(vo.getCorpId());
            logEntity.setEqmtId(list.get(i).getEqmtId());
            logEntity.setCarId(list.get(i).getCarId());
            logEntity.setVrsnId(infoEntity.getVrsnId());
            logEntity.setUpgradeBeginTime(dfhms.format(new Date()));
            logEntity.setUpgradeSt("UPST0200");
            logEntity.setStMsg("UPSM0101");
            logEntity.setUpgradeUser(user.getAcctName());
            saveUpgLog(logEntity);//保存设备版本管理日志实体类
        }
        return list;
    }

    /**
     *
     * @param vo
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-10-23
     * @功能说明：新增外设
     */
    @Transactional
    public void addPerMgr(UpgradeVo vo) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        vo.setCorpId(user.getCorpId());
        Integer count1 = (Integer) sqlMapDao.selectOne("upgrade.checkVrsnName", vo);
        if(count1 > 0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的版本名称已经存在！");
        }
        try {
            /*先保存到ftp*/
            String ftpUpgradePath = UtilConfig.getString("ftp_update_center_parmconfig") + vo.getCarId() + "/"+ vo.getVrsnName()+ "/";;
            FTPUtils.mkdirs(FTPUtils.getInstance().getClient(), ftpUpgradePath);
            FTPUtils.ftpUpload(new ByteArrayInputStream(TxtUtil.getTxtStr(vo.getList()).getBytes()), ftpUpgradePath, "peri.conf");
            /*再保存数据库*/
            //上传日期
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            vo.setUploadDate(df.format(new Date()));
            UpgEqmtVrsnManageInfo infoEntity = new UpgEqmtVrsnManageInfo();
            infoEntity.setVrsnId(UtilString.getUUID());
            infoEntity.setCorpId(user.getCorpId());
            infoEntity.setVrsnName(vo.getVrsnName());
            infoEntity.setVrsnType(vo.getVrsnType());
            infoEntity.setUploadDate(df.format(new Date()));
            infoEntity.setAppUpgrade(vo.getAppUpgrade());
            infoEntity.setFtpUpgradeAdr("peri.conf");
            infoEntity.setLineId(vo.getLineId());
            infoEntity.setCarId(vo.getCarId());
            infoEntity.setEqmtId("");
            infoEntity.setCrtTime(new Date());
            infoEntity.setCrtUser(user.getAcctName());
            infoEntity.setUpdateTime(new Date());
            infoEntity.setUpdateUser(user.getAcctName());
            commonEntityDao.save(infoEntity);
            vo.setVrsnId(infoEntity.getVrsnId());
            for (int i = 0; i <vo.getList().size(); i++) {
                UpgEqmtVrsnParamDetail detailEntity = new UpgEqmtVrsnParamDetail();
                detailEntity.setDetailId(UtilString.getUUID());
                detailEntity.setVrsnId(vo.getVrsnId());
                detailEntity.setParamName(vo.getList().get(i).getParamName());
                detailEntity.setParamValue(vo.getList().get(i).getParamValue());
                detailEntity.setRemark(vo.getRemark());
                detailEntity.setSn(vo.getList().get(i).getSn().add(new BigDecimal(1)));
                commonEntityDao.save(detailEntity);
            }
        } catch (Exception e) {
            throw new BusinessException(MsgType.ERROR.getFlag(), "上传有误！");
        }
    }

    /**
     * @author:JeffXu
     * @throws Exception
     * @email:835264047@qq.com
     * @创建日期:2014-9-19
     * @功能说明：新增参数
     */
    @Transactional
    public void addStatusMgr(UpgradeVo vo) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        vo.setCorpId(user.getCorpId());
        Integer count1 = (Integer) sqlMapDao.selectOne("upgrade.checkVrsnName", vo);
        if(count1 > 0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的版本名称已经存在！");
        }
        try {
            /*先保存到ftp*/
            String ftpUpgradePath = UtilConfig.getString("ftp_update_center_parmconfig") + vo.getCarId() + "/"+ vo.getVrsnName()+ "/";;
            FTPUtils.mkdirs(FTPUtils.getInstance().getClient(), ftpUpgradePath);
            FTPUtils.ftpUpload(new ByteArrayInputStream(TxtUtil.getTxtStr(vo.getList()).getBytes()), ftpUpgradePath, "state.conf");
            /*再保存数据库*/
            //上传日期
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            vo.setUploadDate(df.format(new Date()));
            UpgEqmtVrsnManageInfo infoEntity = new UpgEqmtVrsnManageInfo();
            infoEntity.setVrsnId(UtilString.getUUID());
            infoEntity.setCorpId(user.getCorpId());
            infoEntity.setVrsnName(vo.getVrsnName());
            infoEntity.setVrsnType(vo.getVrsnType());
            infoEntity.setUploadDate(df.format(new Date()));
            infoEntity.setAppUpgrade(vo.getAppUpgrade());
            infoEntity.setFtpUpgradeAdr(vo.getVrsnName());
            infoEntity.setLineId(vo.getLineId());
            infoEntity.setCarId(vo.getCarId());
            infoEntity.setEqmtId("");
            infoEntity.setCrtTime(new Date());
            infoEntity.setCrtUser(user.getAcctName());
            infoEntity.setUpdateTime(new Date());
            infoEntity.setUpdateUser(user.getAcctName());
            commonEntityDao.save(infoEntity);
            vo.setVrsnId(infoEntity.getVrsnId());
            for (int i = 0; i <vo.getList().size(); i++) {
                UpgEqmtVrsnParamDetail detailEntity = new UpgEqmtVrsnParamDetail();
                detailEntity.setDetailId(UtilString.getUUID());
                detailEntity.setVrsnId(vo.getVrsnId());
                detailEntity.setParamName(vo.getList().get(i).getParamName());
                detailEntity.setParamValue(vo.getList().get(i).getParamValue());
                detailEntity.setRemark(vo.getRemark());
                detailEntity.setSn(vo.getList().get(i).getSn().add(new BigDecimal(1)));
                commonEntityDao.save(detailEntity);
            }
        } catch (Exception e) {
            throw new BusinessException(MsgType.ERROR.getFlag(), "上传有误！");
        }
    }


    /**
     * @param vo
     * @author:JeffXu
     * @throws Exception
     * @email:835264047@qq.com
     * @创建日期:2014-9-22
     * @功能说明：删除各种类型
     */
    @Transactional
    public void delUpgrade(UpgradeVo vo) throws Exception {
	    UpgEqmtVrsnManageInfo entity = commonEntityDao.find(vo.getVrsnId(), UpgEqmtVrsnManageInfo.class);
	    /*不同应用升级项，ftp目录不同*/
	    String delPath = "";
	    String ftpUpgradeAdr = "";
	    String tmpStr = "";
	    if(UpgradeVersionTypeEnum.APP_UPGVS.getFlag().equals(vo.getVrsnType())) {
	        if(UpgradeVersionTypeEnum.CORE_BOARD.getFlag().equals(entity.getAppUpgrade())){ // 核心板应用
	        	delPath = UtilConfig.getString("ftp_update_center_coreboard")+entity.getVrsnName();
	        }else if(UpgradeVersionTypeEnum.MAIN_BOARD.getFlag().equals(entity.getAppUpgrade())) {
        	    delPath = UtilConfig.getString("ftp_update_center_mainboard")+entity.getVrsnName();
	        }
	        FTPUtils.deleteFolder(FTPUtils.getInstance().getClient(), FTPUtils.getURL(delPath));
	    }else if(UpgradeVersionTypeEnum.LINE_UPGVS.getFlag().equals(vo.getVrsnType())){
	    	 SysCorpInfoEntity corp = this.getSysCorpInfoByCorpId(entity.getCorpId());
	         BaseLineInfoEntity line = this.getBaseLineInfoByLineId(entity.getLineId());
	         delPath = UtilConfig.getString("ftp_update_center_lineconfig")+corp.getCorpEngAb()+"/"+line.getLineCode()+"/"+entity.getVrsnName();
	         FTPUtils.deleteFolder(FTPUtils.getInstance().getClient(), FTPUtils.getURL(delPath));
	    }else if(UpgradeVersionTypeEnum.CAN_UPGVS.getFlag().equals(vo.getVrsnType())){
	    	  ftpUpgradeAdr = entity.getFtpUpgradeAdr();
	          tmpStr =UtilConfig.getString("ftp_update_center_parmconfig")+ entity.getLineId() +"/"+entity.getVrsnName() +"/"+ ftpUpgradeAdr;
	          delPath = tmpStr.substring(0, tmpStr.lastIndexOf("/"));
	          FTPUtils.deleteFolder(FTPUtils.getInstance().getClient(), FTPUtils.getURL(delPath));
	    }else if(UpgradeVersionTypeEnum.COMM_UPGVS.getFlag().equals(vo.getVrsnType())){
	    	 ftpUpgradeAdr = entity.getFtpUpgradeAdr();
	         tmpStr =UtilConfig.getString("ftp_update_center_parmconfig")+ entity.carId +"/";
	         FTPUtils.delete(tmpStr, ftpUpgradeAdr);
	    }else if(UpgradeVersionTypeEnum.PERI_UPGVS.getFlag().equals(vo.getVrsnType())){
	          ftpUpgradeAdr = entity.getFtpUpgradeAdr();
	          tmpStr =UtilConfig.getString("ftp_update_center_parmconfig")+ entity.carId +"/";
	          FTPUtils.delete(tmpStr, ftpUpgradeAdr);
	          commonEntityDao.delete(entity);
	    }else if(UpgradeVersionTypeEnum.STATE_UPGVS.getFlag().equals(vo.getVrsnType())){
	          ftpUpgradeAdr = entity.getFtpUpgradeAdr();
	          tmpStr =UtilConfig.getString("ftp_update_center_parmconfig")+ entity.carId +"/";
	          FTPUtils.delete(tmpStr, ftpUpgradeAdr);
        }else if(UpgradeVersionTypeEnum.CAR_CANUPGVS.getFlag().equals(entity.getVrsnType())){
            delPath = UtilConfig.getString("ftp_update_center_canconfig")+entity.getVrsnName();
            FTPUtils.deleteFolder(FTPUtils.getInstance().getClient(), FTPUtils.getURL(delPath));
        }
        commonEntityDao.delete(entity);
    }

    /**
     * @author:JeffXu
     * @throws Exception
     * @email:835264047@qq.com
     * @创建日期:2014-9-19
     * @功能说明：新增参数命令
     */
    @Transactional
    public void addUpgradeFile(UpgradeVo vo) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        vo.setCorpId(user.getCorpId());
        Integer count1 = (Integer) sqlMapDao.selectOne("upgrade.checkVrsnName", vo);
        if(count1 > 0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的版本名称已经存在！");
        }
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            vo.setUploadDate(df.format(new Date()));
            UpgEqmtVrsnManageInfo infoEntity = new UpgEqmtVrsnManageInfo();
            infoEntity.setVrsnId(UtilString.getUUID());
            infoEntity.setCorpId(user.getCorpId());
            infoEntity.setVrsnName(vo.getVrsnName());
            infoEntity.setVrsnType(vo.getVrsnType());
            infoEntity.setUploadDate(df.format(new Date()));
            infoEntity.setAppUpgrade(vo.getAppUpgrade());
            infoEntity.setFtpUpgradeAdr(vo.getVrsnName());
            infoEntity.setLineId(vo.getLineId());
            infoEntity.setCarId(vo.getCarId());
            infoEntity.setEqmtId("");
            infoEntity.setCrtTime(new Date());
            infoEntity.setCrtUser(user.getAcctName());
            infoEntity.setUpdateTime(new Date());
            infoEntity.setUpdateUser(user.getAcctName());
            commonEntityDao.save(infoEntity);
            vo.setVrsnId(infoEntity.getVrsnId());
            for (int i = 0; i <vo.getList().size(); i++) {
                UpgEqmtVrsnParamDetail detailEntity = new UpgEqmtVrsnParamDetail();
                detailEntity.setDetailId(UtilString.getUUID());
                detailEntity.setVrsnId(vo.getVrsnId());
                detailEntity.setParamName(vo.getList().get(i).getParamName());
                detailEntity.setParamValue(vo.getList().get(i).getParamValue());
                detailEntity.setRemark(vo.getRemark());
                detailEntity.setSn(vo.getList().get(i).getSn().add(new BigDecimal(1)));
                commonEntityDao.save(detailEntity);
            }
        } catch (Exception e) {
            throw new BusinessException(MsgType.ERROR.getFlag(), "上传有误！");
        }
    }


    /**
     * 预览设备参数信息
     * @param vrsnId
     * @return
     * @throws Exception
     */
    @Transactional
    public List<UpgEqmtVrsnParamDetail> getDetailByVrsnId(String vrsnId) throws Exception{
        List<UpgEqmtVrsnParamDetail> list =  PubUtil.convertListMapToObject(this.sqlMapDao.selectList("upgrade.getDetailByVrsnId", vrsnId), UpgEqmtVrsnParamDetail.class);
        return list;
    }

    /**
     * @author:JeffXu
     * @throws Exception
     * @email:835264047@qq.com
     * @创建日期:2014-9-19
     * @功能说明：获取设备参数信息
     */
    @Transactional
    public List<UpgEqmtIssuedParamTemp> getParamByVrsnType(String vrsnType) throws Exception{
        List<UpgEqmtIssuedParamTemp> list =  PubUtil.convertListMapToObject(this.sqlMapDao.selectList("upgrade.getParamByVrsnType", vrsnType), UpgEqmtIssuedParamTemp.class);
        return list;
    }

    /**
     * 获取设备下发参数模板
     * @param paramIssue
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
//    @SuppressWarnings("unchecked")
//    public List<UpgEqmtIssuedParamTemp> getIssuedParam(String paramIssue) {
//        List<UpgEqmtIssuedParamTemp> list = PubUtil.convertListMapToObject(
//                this.sqlMapDao.selectList("upgrade.getIssuedParam", paramIssue), UpgEqmtIssuedParamTemp.class);
//        return list;
//    }
    @SuppressWarnings("unchecked")
    public List<UpgEqmtIssuedParamVo> getIssuedParam(String paramIssue) {
    	List<UpgEqmtIssuedParamVo> list = null;
    	if("12".equals(paramIssue)){
    		list = PubUtil.convertListMapToObject(
    				this.sqlMapDao.selectList("upgrade.getChStanderdIssuedParam"), UpgEqmtIssuedParamVo.class);
    	}else{
    		list = PubUtil.convertListMapToObject(
    				this.sqlMapDao.selectList("upgrade.getIssuedParam", paramIssue), UpgEqmtIssuedParamVo.class);
    	}
    	
        return list;
    }

    /**
     * 查询命令升级日志
     * @param vo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    public Pagination searchLogPage(UpgradeVo vo) throws Exception{
        Pagination page = this.myBatisPage("upgrade.searchLogPageCnt","upgrade.searchLogPage", vo,UpgEqmtVrsnManageInfo.class);
        return page;
    }

    /**
     * 查询远程文件升级
     * @param vo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("static-access")
    @Transactional
    @LeftOrgAnnotation()
    public Pagination searchUpgrade(UpgradeVo vo) throws Exception {
        Pagination page = this.myBatisPage("upgrade.searchUpgradeCount", "upgrade.searchUpgrade", vo,UpgEqmtVrsnManageInfo.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("lineName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo1 = new FillParamsVo("lineId", map);
        map = new HashMap<String,String>();
        map.put("licPltNo", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("carId", map);
        map = new HashMap<String,String>();
        map.put("carInCd", "carInCd");
        FillParamsVo vo3 = new FillParamsVo("carId", map);
        codeDscValue.fillInfoValue(page.getData(), new String[]{GlobalConst.CACHE_KEY_BASE_CAR_INFO, GlobalConst.CACHE_KEY_BASE_LINE_INFO,GlobalConst.CACHE_KEY_BASE_CAR_INFO}, vo1, vo2,vo3);
        return page;
    }

    /**
     * 升级日志
     * @param vo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("static-access")
    @Transactional
    @LeftOrgAnnotation()
    public Pagination searchUpgradeLog(UpgradeVo vo) throws Exception {
        if(!"".equals(vo.getAppUpgrade()) && vo.getAppUpgrade()!=null){
            switch (vo.getAppUpgrade()) {
                case "1": vo.setLogType("ULOG0001");
                    break;
                case "2": vo.setLogType("ULOG0002");
                    break;
                case "3": vo.setLogType("ULOG0007");
                    break;
                case "5": vo.setLogType("ULOG0011");
                    break;
                case "6": vo.setLogType("ULOG0012");
                    break;
                case "7": vo.setLogType("ULOG0013");
                    break;
                case "8": vo.setLogType("ULOG0014");
                    break;
                case "9": vo.setLogType("ULOG0015");
                    break;
                case "10": vo.setLogType("ULOG0016");
                    break;
                case "11": vo.setLogType("ULOG0017");
                    break;
                case "12": vo.setLogType("ULOG0018");
                    break;
            }
        }

//        List<UpgEqmtVrsnManageInfo> list = PubUtil.convertListMapToObject(
//                this.sqlMapDao.selectList("upgrade.getAppUpgLogList", vo), UpgEqmtVrsnManageInfo.class);
//        DateFormat  dfhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        if(list!=null){
//            for(int i = 0; i < list.size(); i++){
//                if("UPST0200".equals(list.get(i).getUpgradeSt())){
//                    Date begin = dfhms.parse(list.get(i).getUpgradeBeginTime());
//                    String a = dfhms.format(new Date());
//                    Date now = dfhms.parse(a);
//                    long diff = (now.getTime() - begin.getTime())/1000;
//                    if((int)diff>180){
//                        Map<String, Object> paramMap = new HashMap<String, Object>();
//                        paramMap.put("logId", list.get(i).getLogId());
//                        this.sqlMapDao.update("upgrade.uptAppUpgLogList", paramMap);
//                    }
//                }
//            }
//        }
        vo.setEndTime(DateTool.getCurrentSysDate());
        Pagination page = this.myBatisPage("upgrade.getAppUpgLogCnt", "upgrade.getAppUpgLogList", vo,UpgEqmtVrsnManageInfo.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("lineName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo1 = new FillParamsVo("lineId", map);
        map = new HashMap<String,String>();
        map.put("licPltNo", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("carId", map);
        map = new HashMap<String,String>();
        map.put("eqmtCd", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo3 = new FillParamsVo("eqmtId", map);
        codeDscValue.fillInfoValue(page.getData(), new String[]{GlobalConst.CACHE_KEY_BASE_CAR_INFO, GlobalConst.CACHE_KEY_BASE_LINE_INFO,GlobalConst.CACHE_KEY_BASE_EQMT_INFO}, vo1, vo2,vo3);
        return page;
    }

    /**
     *
     * @param vo
     * @return
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-22
     * @功能说明：获取升级版本名称
     */
    @SuppressWarnings("unchecked")
    @Transactional
    @LeftOrgAnnotation()
    public  List<UpgEqmtVrsnManageInfo>  getVersionName(UpgradeVo  vo){
        List<UpgEqmtVrsnManageInfo> list=null;
        if("VERS0002".equals(vo.getVrsnType())){
            list = PubUtil.convertListMapToObject(sqlMapDao.selectList("upgrade.getVersionNameByLine", vo), UpgEqmtVrsnManageInfo.class);
        }else if("APUP0002".equals(vo.getAppUpgrade())||"VERS0012".equals(vo.getVrsnType())){
            list = PubUtil.convertListMapToObject(sqlMapDao.selectList("upgrade.getVersionNameByCarModel", vo), UpgEqmtVrsnManageInfo.class);
        }else if("APUP0001".equals(vo.getAppUpgrade())){
            list = PubUtil.convertListMapToObject(sqlMapDao.selectList("upgrade.getVersionName", vo), UpgEqmtVrsnManageInfo.class);
        }
        return list;
    }

    /**
     *
     * @param logEntity
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-28
     * @功能说明：新增日志
     */
    @Transactional
    public void saveUpgLog(UpgEqmtVrsnManageLog logEntity) {
        commonEntityDao.save(logEntity);
    }

    /**
     *
     * @param VrsnId
     * @return
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-26
     * @功能说明：查询FTP地址
     */
    @Transactional
    public UpgEqmtVrsnManageInfo getUpgEqmtVrsnByVrsnId(String VrsnId){
        UpgEqmtVrsnManageInfo upgEqmtVrsnManageInfo = commonEntityDao.find(VrsnId, UpgEqmtVrsnManageInfo.class);
        return upgEqmtVrsnManageInfo;
    }

    /**
     *
     * @param vo
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-25
     * @功能说明： 文件升级
     */
    @LeftOrgAnnotation()
    @Transactional
    public void softwareUpgrade(UpgradeVo vo)throws Exception{
        SysUserEntity user = this.getCurrentUser().getUser();
        vo.setCorpId(user.getCorpId());
        switch (vo.getAppUpgrade()) {
            case "APUP0001":  vo.setModule("1");vo.setType("ULOG0001");
                break;
            case "APUP0002":  vo.setModule("2");vo.setType("ULOG0007");
                break;
            case "VERS0002":  vo.setModule("4");vo.setType("ULOG0002");
                break;
            case "VERS0012":  vo.setModule("9");vo.setType("ULOG0018");
                break;
        }
        for (int i = 0; i < vo.getEqmtIdArr().length; i++) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            DateFormat dfhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            UpgEqmtVrsnManageInfo upgEqmtVrsnManageInfo = getUpgEqmtVrsnByVrsnId(vo.getAppupgradeidArr()[i]);
            upgEqmtVrsnManageInfo.setModule(vo.getModule());
            Map<String, Object> ftpUpgradeInfo = getFtpUpgradeAddrInfo(upgEqmtVrsnManageInfo);
            String ftpUpgradeDirePath =  ftpUpgradeInfo.get("ftpUpgradeDire").toString();
            String ftpUpgradeFileName = ftpUpgradeInfo.get("ftpUpgradeFile").toString();
            //新增日志
            UpgEqmtVrsnManageLog logEntity = new UpgEqmtVrsnManageLog();
            logEntity.setLogId(UtilString.getUUID());
            logEntity.setLogType(vo.getType());
            logEntity.setCorpId(vo.getCorpId());
            logEntity.setEqmtId(vo.getEqmtIdArr()[i]);
            logEntity.setCarId(vo.getCarIdArr()[i]);
            logEntity.setVrsnId(upgEqmtVrsnManageInfo.getVrsnId());
            logEntity.setUpgradeBeginTime(dfhms.format(new Date()));
            logEntity.setUpgradeSt("UPST0200");
            logEntity.setStMsg("UPSM0101");
            logEntity.setUpgradeUser(user.getAcctName());
            saveUpgLog(logEntity);
            //开启后台升级进程
            String upgradeCommandStr = "{'devId': '"+ vo.getEqmtCdArr()[i] +"','canId': '05', 'type':'0','folder':'"+ ftpUpgradeDirePath +"','file': '"+ ftpUpgradeFileName +"','module': '"+ vo.getModule() +"'}";
            UpgradeProcessor processor = new UpgradeProcessor("05", upgradeCommandStr, taskExecutor);
            processor.process();

        }
    }

    /**
     *
     * @param vo
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-22
     * @功能说明：设备文件下载  查询
     */
    @SuppressWarnings("static-access")
    @Transactional
    public Pagination searchDevLogUploadPage(UpgradeVo vo) throws Exception {
        Pagination page = this.myBatisPage("upgrade.getDevLogUploadCnt", "upgrade.getDevLogUploadList", vo, UpgEqmtVrsnManageLog.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("licPltNo", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo1 = new FillParamsVo("carId", map);
        map = new HashMap<String,String>();
        map.put("eqmtCd", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("eqmtId", map);
        codeDscValue.fillInfoValue(page.getData(), new String[]{GlobalConst.CACHE_KEY_BASE_CAR_INFO, GlobalConst.CACHE_KEY_BASE_EQMT_INFO}, vo1, vo2);
        return page;
    }

    /**
     *
     * @param vo
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-9-22
     * @功能说明：设备文件下载  上传
     */
    @Transactional
    public void devLogUpload(UpgradeVo vo) throws Exception{
        List<BaseEqmtInfoEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("upgrade.getEqmtInfoByCarId", vo.getCarId()), BaseEqmtInfoEntity.class);
        if(PubUtil.isEmpty(list)){
            return;
        }
        SysUserEntity user = this.getCurrentUser().getUser();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String eqmtId=list.get(0).getEqmtId();
        String eqmtCd=list.get(0).getEqmtCd();
        UpgEqmtVrsnManageLog logEntity=new UpgEqmtVrsnManageLog();
        logEntity.setLogId(UtilString.getUUID());
        logEntity.setCarId(vo.getCarId());
        logEntity.setCorpId(user.getCorpId());
        logEntity.setEqmtId(eqmtId);
        logEntity.setLogType("ULOG0010");
        logEntity.setIssuedQueryDate(vo.getReportDate());
        logEntity.setUpgradeBeginTime(df.format(new Date()));
        logEntity.setUpgradeSt("UPST0200");
        logEntity.setUpgradeUser(user.getName());
        logEntity.setVrsnId(vo.getReportDate());
        logEntity.setStMsg("UPST0200");
        commonEntityDao.save(logEntity);
        //开启后台升级进程
        String commandStr = "{'devId': '"+eqmtCd+"','reportDate':'"+vo.getReportDate()+"','type':'06'}";
        DevLogUploadProcessor processor = new DevLogUploadProcessor(logEntity.getLogId(),commandStr,taskExecutor,this);
        processor.process();
    }

    @Transactional
    public void updateUpgLog(UpgEqmtVrsnManageLog logEntity) {
        sqlMapDao.update("upgrade.updateUpgEqmtVrsnManageLog", logEntity);
    }
}
